package com.lundao.blog.service.impl;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lundao.blog.mapper.BlogMapper;
import com.lundao.blog.domain.Blog;
import com.lundao.blog.service.IBlogService;
import com.lundao.collect.service.ICollectService;
import com.lundao.common.utils.SecurityUtils;
import com.lundao.service.ICommentService;
import com.lundao.common.utils.DateUtils;
import com.lundao.common.utils.uuid.IdUtils;

import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import static com.lundao.common.utils.SecurityUtils.getUserId;

@Service
public class BlogServiceImpl implements IBlogService {

    private static final Logger log = LoggerFactory.getLogger(BlogServiceImpl.class);

    @Value("${server.port:8080}")
    private int port;

    @Autowired
    private BlogMapper blogMapper;
    @Autowired
    private SqlSessionFactory sqlSessionFactory;
    @Autowired
    private ICollectService collectService;
    @Autowired
    private ICommentService commentService;

    /* ========== 以下方法保持你原有逻辑不变 ========== */
    @Override
    public Blog selectBlogByBlogId(String blogId) {
        return blogMapper.selectBlogByBlogId(blogId);
    }

    @Override
    public List<Blog> selectBlogList(Blog blog) {
        List<Blog> blogs = blogMapper.selectBlogList(blog);
        if (!blogs.isEmpty()) {
            List<String> blogIds = blogs.stream().map(Blog::getBlogId).collect(Collectors.toList());
            Map<String, Integer> collectMap = collectService.batchSelectCollectCount(blogIds);
            Map<String, Integer> commentMap = commentService.batchSelectCommentCount(blogIds);
            blogs.forEach(b -> {
                b.setCollectCount(collectMap.getOrDefault(b.getBlogId(), 0));
                b.setCommentCount(commentMap.getOrDefault(b.getBlogId(), 0));
            });
        }
        return blogs;
    }
    @Value("${deepseek.api-key}")
    private String deepseekApiKey;

    @Override
    public List<Blog> selectCollectedBlogListByUserId(Long userId) {
        return blogMapper.selectCollectedBlogListByUserId(userId);
    }


    @Override
    public int insertBlog(Blog blog) {
        blog.setCreateTime(DateUtils.getNowDate());
        blog.setBlogId(IdUtils.randomUUID());
        blog.setUserId(Math.toIntExact(getUserId()));
        int rows = blogMapper.insertBlog(blog);

        /* ===== AI机器人评论（异步，带完整日志） ===== */
        // 在 BlogServiceImpl.insertBlog() 的异步块里

        CompletableFuture.runAsync(() -> {
            try {
                // 1. 调用 DeepSeek 生成评论
                log.info("【AI评论】异步任务开始，准备调用 DeepSeek，blogId={}", blog.getBlogId());
                String prompt = "请为以下博客写一条简短、有趣、带 emoji 的评论区回复，不超过50字：\n标题："
                        + blog.getTitle() + "\n摘要：" + blog.getSummary();

                RestTemplate rest = new RestTemplate();
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                headers.set("Authorization", "Bearer " + deepseekApiKey); // ✅ 只用于 DeepSeek

                JSONObject body = new JSONObject();
                body.put("model", "deepseek-chat");
                body.put("messages", new JSONArray().fluentAdd(
                        new JSONObject().fluentPut("role", "user").fluentPut("content", prompt)
                ));
                body.put("temperature", 0.8);
                body.put("max_tokens", 100);

                HttpEntity<String> entity = new HttpEntity<>(body.toJSONString(), headers);
                String resp = rest.postForObject("https://api.deepseek.com/v1/chat/completions", entity, String.class);

                String aiComment = JSONObject.parseObject(resp)
                        .getJSONArray("choices")
                        .getJSONObject(0)
                        .getJSONObject("message")
                        .getString("content")
                        .trim();
                log.info("【AI评论】DeepSeek 返回内容：{}", aiComment);

                // 2. 调用本地 /robot-comment 接口（不带 Authorization）
                HttpHeaders localHeaders = new HttpHeaders();
                localHeaders.setContentType(MediaType.APPLICATION_JSON);

                JSONObject req = new JSONObject();
                req.put("blogId", blog.getBlogId());
                req.put("content", aiComment);

                HttpEntity<String> commentEntity = new HttpEntity<>(req.toJSONString(), localHeaders);
                String url = "http://localhost:" + port + "/api/ai/robot-comment";
                JSONObject result = rest.postForObject(url, commentEntity, JSONObject.class);
                log.info("【AI评论】结果：{}", result);
            } catch (Exception e) {
                log.error("【AI评论】异步调用失败", e);
            }
        });
        return rows;
    }

    /**
     * 批量新增博客
     *
     * @param blogs 博客List
     * @return 结果
     */
    @Override
    public int batchInsertBlog(List<Blog> blogs)
    {
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        int count = 0;
        if (!CollectionUtils.isEmpty(blogs)) {
            try {
                for (int i = 0; i < blogs.size(); i++) {
                    int row = blogMapper.insertBlog(blogs.get(i));
                    // 防止内存溢出，每100次提交一次,并清除缓存
                    boolean bool = (i >0 && i%100 == 0) || i == blogs.size() - 1;
                    if (bool){
                        sqlSession.commit();
                        sqlSession.clearCache();
                    }
                    count = i + 1;
                }
            }catch (Exception e){
                e.printStackTrace();
                // 没有提交的数据可以回滚
                sqlSession.rollback();
            }finally {
                sqlSession.close();
                return count;
            }
        }
        return count;
    }

    /**
     * 修改博客
     *
     * @param blog 博客
     * @return 结果
     */
    @Override
    public int updateBlog(Blog blog)
    {
        return blogMapper.updateBlog(blog);
    }

    /**
     * 批量删除博客
     *
     * @param blogIds 需要删除的博客主键
     * @return 结果
     */
    @Override
    public int deleteBlogByBlogIds(String[] blogIds)
    {
        return blogMapper.deleteBlogByBlogIds(blogIds);
    }

    /**
     * 删除博客信息
     *
     * @param blogId 博客主键
     * @return 结果
     */
    @Override
    public int deleteBlogByBlogId(String blogId)
    {
        return blogMapper.deleteBlogByBlogId(blogId);
    }


}
